package com.example.stu.service.impl;

import com.example.stu.entity.Result;
import com.example.stu.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Date: 2021/2/26
 * @Author: 黄先军
 * @Description:
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码到邮件里面，然后把验证码存在redis里面，验证码的键为邮箱号
     * @param email
     * @return
     */
    @Override
    public Result sendEmail(String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1292148080@qq.com");
        message.setTo(email);
        message.setSubject("你的注册验证码");

        //生成4位数的验证码包含数字和字母
        String ZiMu = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGJKLZXCVBNM1234567890";
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(ZiMu.length());
            char c = ZiMu.charAt(index);
            result += c;
        }
        //邮件内容-自定义
        message.setText(result);
        try {
            //用email做为key
            redisTemplate.opsForValue().set(email,result);
            //获取验证码
            //String redisYzm = redisTemplate.opsForValue().get(email);
            //设置180秒的过期时间
            redisTemplate.expire(email,180, TimeUnit.SECONDS);
            mailSender.send(message);
            return new Result(true, "发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return new Result(true, "发送普通邮件成功");
        }
    }




}
